#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <string>

const int size = 4096;
const int projid = 0x66;
const int gmode = 0666;
const std::string pathname = ".";

int main() {
    int shmid;
    void *shm;

    key_t key = ftok(pathname.c_str(), projid);
    if (key < 0)
    {
        perror("ftok");
        exit(1);
    }
    printf("key: 0x%x\n", key);

    shmid = shmget(key, size, gmode);
    if (shmid < 0) {
        perror("shmget");
        exit(1);
    }

    shm = static_cast<char*>(shmat(shmid, NULL, 0));
    if ((long long)shm < 0)
    {
        perror("shmat");
        exit(1);
    }


    printf("Message from shared memory: %s\n", (char*)shm);

    if (shmdt(shm) < 0) {
        perror("shmdt");
        exit(1);
    }


    if (shmctl(shmid, IPC_RMID, nullptr) < 0) {
        perror("shmctl");
        exit(1);
    }

    return 0;
}